package com.hopes.bizz.protocol.hj212.bo;

import cn.allbs.hj212.enums.HjDataFlag;
import cn.allbs.hj212.format.T212Mapper;
import cn.allbs.hj212.model.HjData;
import lombok.SneakyThrows;

import java.util.List;

/**
 * @author lyb
 * @version 1.0
 * @description: 解析 HJ212 数据
 * @date 2023/3/7 21:05
 */
public class HjDataParse {

    private String data;

    private HjData hjData;

    @SneakyThrows
    public HjDataParse(String data) {
        this.data = data;
        T212Mapper mapper = new T212Mapper().enableDefaultParserFeatures().enableDefaultVerifyFeatures();
        HjData hjData = mapper.readData(this.data);
        this.hjData = hjData;
    }

    // 判断是否是拆包
    public Boolean isUpPacket() {
        if (this.hjData == null) {
            return false;
        }
        List<HjDataFlag> dataFlag = hjData.getDataFlag();
        Integer pNum = hjData.getPNum();
        Integer pNo = hjData.getPNo();
        return dataFlag != null && dataFlag.contains(HjDataFlag.D) && pNo != null && pNum != null && pNum > 1;
    }

    // 判断是否需要合并，必须保证传输包顺序一致
    public Boolean isMerge() {
        if (this.hjData == null) {
            return false;
        }
        Integer pNo = hjData.getPNo();
        Integer pNum = hjData.getPNum();
        return pNo.equals(pNum);
    }

    public String getKey() {
        String mn = hjData.getMn();
        String cn = hjData.getCn();
        String st = hjData.getSt();
        String dataTime = hjData.getCp().getDataTime();
        return String.join(":", mn, cn, st, dataTime);
    }

    public HjData getHjData() {
        return hjData;
    }
}
